import { Provider } from '@nestjs/common';
import { MqttClient } from 'mqtt';
import * as mqtt from 'mqtt';
// import * as md5 from 'md5';
import { MQTT_PUBLISH_CLIENT_PROVIDER } from '../constants/mqtt.constant';
import { ConfigType } from '@nestjs/config';
import { MqttConfigRegister } from '../../config/registers/mqtt.register';

/** 创建Mqtt Publish Client Provider方法 */
export const createMqttPublishClientProvider = (): Provider => ({
  provide: MQTT_PUBLISH_CLIENT_PROVIDER,
  useFactory: (mqttConfig: ConfigType<typeof MqttConfigRegister>): MqttClient =>
    mqtt.connect(mqttConfig.url + ':' + mqttConfig.port, {
      keepalive: 60,
      clientId: 'mqtt-publisher'
      // username: 'mqtt-publisher',
      // password: md5('mqtt-publisher')
    }),
  inject: [MqttConfigRegister.KEY]
});
